using B.S.NewMedical.Api.Write.Application.Command.Doctor;
using B.S.NewMedical.Domain.Appointment;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace B.S.NewMedical.Api.Write.Application.Handler.Doctor
{
    /// <summary>
    /// 开检验单处理器
    /// </summary>
    public class AddLaborderHandler : IRequestHandler<AddLaborderCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Visit> _visitRepository;
        private readonly IBaseRepository<Laborder> _laborderRepository;
        private readonly ILogger<AddLaborderHandler> _logger;

        public AddLaborderHandler(
            IBaseRepository<Visit> visitRepository,
            IBaseRepository<Laborder> laborderRepository,
            ILogger<AddLaborderHandler> logger)
        {
            _visitRepository = visitRepository;
            _laborderRepository = laborderRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(AddLaborderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理开检验单，就诊ID: {VisitId}", request.VisitId);

                // 参数验证
                if (request.VisitId <= 0)
                    return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "就诊ID不能为空" };

                if (string.IsNullOrWhiteSpace(request.ItemName))
                    return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "检验项目不能为空" };

                if (request.Price <= 0)
                    return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "检验费用必须大于0" };

                // 检查就诊记录是否存在
                var visit = await _visitRepository.GetAll()
                    .FirstOrDefaultAsync(v => v.Id == request.VisitId && !v.IsDeleted, cancellationToken);

                if (visit == null)
                    return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "就诊记录不存在" };

                // 生成申请单号（时间戳+随机数）
                var orderNo = $"JY{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(1000, 9999)}";

                // 创建检验申请单
                var laborder = new Laborder
                {
                    Visit_id = request.VisitId,
                    Order_no = orderNo,
                    Item_name = request.ItemName,
                    Price = request.Price,
                    Status = "待收费",
                    Create_time = DateTime.Now,
                    Result_text = "", // 初始为空，检验后录入
                    IsDeleted = false
                };

                await _laborderRepository.CreateAsync(laborder);

                _logger.LogInformation("开检验单成功，检验单ID: {LaborderId}，申请单号: {OrderNo}", 
                    laborder.Id, orderNo);

                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "开检验单成功",
                    Data = laborder.Id
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开检验单时发生错误，就诊ID: {VisitId}", request.VisitId);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Fail,
                    Msg = "开检验单失败"
                };
            }
        }
    }
} 